    //
//  ImageSenderController.m
//  NetImager
//
//  Created by li hongliang on 10-9-8.
//  Copyright 2010 sweet-home. All rights reserved.
//

#import "ImageSenderController.h"
#import "UserSetting.h"
#import "PictureAnimation.h"


#define DOUBANBTN	0
#define TWITTERBTN	1
#define FLICKERBTN  2
#define FACEBOOKBTN 3

//@interface UIAlertView(SenderSetting){
//	NSString *title;
//}
//@end

@implementation ImageSenderController

@synthesize image;
@synthesize delegate = _delegate;


#pragma mark SenderViewDelegate
- (void) appearActivityViewDelegate
{
	indicatorView = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
	indicatorView.frame = CGRectMake(0.0f, 0.0f, 32.0f, 32.0f);
	[indicatorView setCenter: self.view.center];
	[self.view addSubview:indicatorView];
	[self.view bringSubviewToFront:indicatorView];
	[indicatorView startAnimating];
	self.navigationController.navigationBarHidden = YES;
	self.navigationController.toolbarHidden = YES;
}

- (void) doneActivityViewDelegate
{
	[indicatorView stopAnimating];
	self.navigationController.navigationBarHidden = NO;
	self.navigationController.toolbarHidden = NO;
}

- (void) didAlertViewDelegate:(NSString *)title message:(NSString *)message
{
	UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:title 
													 message:message 
													delegate:self 
										   cancelButtonTitle:nil 
										   otherButtonTitles:@"OK",nil] autorelease];
	[alert show];
}

#pragma mark fix image size

- (void) fixImageRectWidth: (CGSize *)imageSize  frameSize:(CGSize)frameSize;
{
	   CGFloat offsetRate = frameSize.width / imageSize->width;
	   imageSize->width = imageSize->width * offsetRate;
	   imageSize->height = imageSize->height * offsetRate;
}

- (void) fixImageRectHeight: (CGSize *)imageSize  frameSize:(CGSize)frameSize;
{
		CGFloat offsetRate = frameSize.height / imageSize->height;
		imageSize->width = imageSize->width * offsetRate;
		imageSize->height = imageSize->height * offsetRate;
}


- (CGRect) calcImageRect: (CGSize)size
{
	CGSize imageSize = size;
	CGRect frame ;	
	
	frame.origin = CGPointMake(0.0f, 0.0f);
	
	UIDevice *device = [UIDevice currentDevice];
	if( (device.orientation == UIDeviceOrientationPortrait)
	   || (device.orientation == UIDeviceOrientationPortraitUpsideDown))
	{
		frame.size = CGSizeMake(320.0f, 460.0f);
		[self fixImageRectWidth: &imageSize  frameSize:frame.size];
		[self fixImageRectHeight: &imageSize  frameSize:frame.size];
		[self fixImageRectWidth: &imageSize  frameSize:frame.size];

	}
	else if( (device.orientation == UIDeviceOrientationLandscapeLeft)
			|| (device.orientation == UIDeviceOrientationLandscapeRight)) 
	{
		frame.size = CGSizeMake(480.0f, 300.0f);

		[self fixImageRectHeight: &imageSize  frameSize:frame.size];
		[self fixImageRectWidth: &imageSize  frameSize:frame.size];
		[self fixImageRectHeight: &imageSize  frameSize:frame.size];
		
	}
	CGPoint point = CGPointMake((frame.size.width-imageSize.width) / 2, (frame.size.height-imageSize.height)/2 );
	
	return CGRectMake(point.x, point.y, imageSize.width, imageSize.height);	
}

#pragma mark load view

- (void) loadImageView: (id)sender
{
	NSMutableArray *buttons = [[[NSMutableArray alloc] init] autorelease];
	
	UIBarButtonItem *item = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction
																		   target:self action:@selector(popSenderMenu:)] autorelease];
	[buttons addObject:item];
	//[item release];
	
	UIBarButtonItem *flexibleSpaceItem = [[[UIBarButtonItem alloc]
										   initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
										   target:nil
										   action:NULL] autorelease];
	[buttons addObject:flexibleSpaceItem];
//
//	item = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemEdit
//														  target:self action:@selector(roateLayer:)] autorelease];
//	[buttons addObject:item];
	
	
	
	self.toolbarItems = buttons;
	self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"Back" 
																			  style:UIBarButtonItemStylePlain 
																			 target:self 
																			 action:@selector(toPickerController:)] autorelease];
	

	UINavigationBar *navBar = self.navigationController.navigationBar;
	navBar.barStyle = UIBarStyleBlackTranslucent;
	navBar.translucent = YES;
	
	UIToolbar *toolbar = self.navigationController.toolbar;
	toolbar.barStyle = UIBarStyleBlackTranslucent;
	toolbar.translucent = YES;
	[toolbar setItems:buttons animated:YES];
	[toolbar sizeToFit];
	
	self.navigationController.delegate = self;	
	
	CGRect imageRect = [self calcImageRect: image.size];
	imageView = [[UIImageView alloc] initWithFrame:imageRect];
    [imageView setImage:image];

	
	[self.view addSubview:imageView];
	
	[self.navigationController setNavigationBarHidden:NO];
	[self.navigationController setToolbarHidden:NO];	

	[imageView release];
	
}
//
//- (void) roateLayer:(id) sender
//{
//	CALayer * layer = imageView.layer;
//}

// Implement loadView to create a view hierarchy programmatically, without using a nib.
//
- (void)loadView {
	[super loadView];
	[self.navigationController setNavigationBarHidden:YES];
	[self.navigationController setToolbarHidden:YES];	
	
	
	CGRect frame = [[UIScreen mainScreen] applicationFrame];
	UIView *view = [[[UIView alloc] initWithFrame:frame] autorelease];
	view.backgroundColor = [UIColor blackColor];		
	self.view = view;
	
	view.autoresizesSubviews = YES;
	view.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
	
	//[self performSelectorOnMainThread:@selector(loadImageView:) withObject:nil waitUntilDone:NO];	
	[self loadImageView:self];
	senderFactory = [[SenderFactory alloc] init];
}


#pragma mark navigationBar & tool bar action 

- (void) toPickerController:(id)sender
{
	if(self.delegate != nil && [self.delegate conformsToProtocol:@protocol(ImageSenderControllerDelegate)])
	{
		[self.delegate toPickerController:sender];
	}
}

- (void) popSenderMenu: (id) sender
{
	self.navigationController.toolbarHidden = YES;
	self.navigationController.navigationBarHidden = YES;
	
	UIActionSheet *menu = [[[UIActionSheet alloc] initWithTitle:@"Choose a sender" 
													  delegate:self 
											 cancelButtonTitle:@"Hidden" 
										destructiveButtonTitle:nil  
											 otherButtonTitles:@"Douban",@"Twitter", @"Flicker", @"FaceBook", nil] autorelease];
	menu.alpha = 0.5f;
	[menu showInView:self.view];
}

#pragma mark popup menu action


- (void) actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
	NSLog(@"Click button index: %d", buttonIndex);
	self.navigationController.toolbarHidden = NO;
	self.navigationController.navigationBarHidden = NO;

	NSString *siteKey;
	
	switch (buttonIndex) {
		case DOUBANBTN:
			siteKey = @"DouBan";			
			break;
		case TWITTERBTN:
			siteKey = @"Twitter";
			break;
		case FLICKERBTN:
			siteKey = @"Flicker";
			break;
		case FACEBOOKBTN:
			siteKey = @"Facebook";
			break;
		default:
			return;
			break;
	}

	UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:siteKey 
													message:@"" 
												   delegate:self 
										  cancelButtonTitle:@"Cancel" 
										  otherButtonTitles:@"Save & Send", nil] autorelease];
	UserSetting *userSetting = [[UserSetting alloc] init];
	[userSetting loadUserSetting:siteKey];
	[alert addTextFieldWithValue:userSetting.userName label:@"Enter Name"];
	[alert addTextFieldWithValue:userSetting.passWord label:@"Enter Password"];
	[userSetting release];
	// Name field
	UITextField *tf = [alert textFieldAtIndex:0];
	tf.clearButtonMode = UITextFieldViewModeWhileEditing;
	tf.keyboardType = UIKeyboardTypeAlphabet;
	tf.keyboardAppearance = UIKeyboardAppearanceAlert;
	tf.autocapitalizationType = UITextAutocapitalizationTypeWords;
	tf.autocorrectionType = UITextAutocorrectionTypeNo;
	
	tf = [alert textFieldAtIndex:1];
	tf.clearButtonMode = UITextFieldViewModeWhileEditing;
	tf.secureTextEntry = YES;
	tf.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
	tf.keyboardAppearance = UIKeyboardAppearanceAlert;
	tf.autocapitalizationType = UITextAutocapitalizationTypeWords;
	tf.autocorrectionType = UITextAutocorrectionTypeNo;
	[alert show];
}

- (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
	if(buttonIndex == 1)  // save & send
	{
		if([alertView.title caseInsensitiveCompare:@"DouBan"] == 0)
		{
			[UserSetting writeUserSetting:alertView.title
								 username:[[alertView textFieldAtIndex:0] text] 
								 password:[[alertView textFieldAtIndex:1] text] 
								uploadURL:@"http://weiyesoft.3322.org/uploads.php"];
		}
		else {
			[UserSetting writeUserSetting:alertView.title
								 username:[[alertView textFieldAtIndex:0] text] 
								 password:[[alertView textFieldAtIndex:1] text] 
								uploadURL:@""];
		}
		NSLog(@"Send to %@", alertView.title);
	
		
		UIImage *sendImage = [PictureAnimation rotateImage:self.image orientation:-1];
		[senderFactory sendTest:alertView.title image:sendImage delegate:self];
	}
	
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];	
}

#pragma mark rotate

- (void) willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
	NSArray *subViews = self.view.subviews;
	for (UIImageView *view in subViews){
		CGRect imageRect = [self calcImageRect: image.size];
		view.frame = imageRect;
	}
	
}

// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    //return (interfaceOrientation == UIInterfaceOrientationPortrait);
	return YES;
}


- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
	[self.delegate release];
	[self.image release];
	//[self.indicatorView release];
	[senderFactory release];
    [super dealloc];
}


@end
